package com.example.license.service.impl;

import com.example.license.create.CreateLicense;
import com.example.license.entity.LicenseCreatorParam;
import com.example.license.service.LicenseCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author YangJian
 * @Description TODO
 * @createTime 2022年03月23日 10:11
 */
@Service
@Slf4j
public class LicenseCreateServiceImpl implements LicenseCreateService {
    @Override
    public void licenseCreate(LicenseCreatorParam param) throws Exception {
        CreateLicense createLicense = new CreateLicense();
        createLicense.setParam("/param.properties",param);
        createLicense.create();
    }
    @Override
    public HttpServletResponse download(HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File("license.lic");
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream("license.lic"));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            this.log.info("服务器端证书下载成功!");
        } catch (IOException ex) {
            this.log.error("服务器端证书下载失败!");
            ex.printStackTrace();
        }
        return null;
    }
}
